$(function () {
    getArticleCate();

    var index;
    // 添加分类
    $('#addCate').on('click', function () {
        index = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '添加文章分类',
            content: $('#tpl-add').html()
        })
    });

    // 提交添加参数表单
    $('body').on('submit', '#addForm', function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/my/article/addcates",
            data: $(this).serialize(),
            success: function (response) {
                if (response.status !== 0) {
                    return layer.msg('添加失败!');
                };
                layer.msg('添加成功!');
                getArticleCate();
                layer.close(index);
            }
        });
    })

    // 修改参数
    $('tbody').on('click', '.editCate', function () {
        const id = $(this).attr('data-id');
        index = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '修改文章分类',
            content: $('#tpl-edit').html()
        });

        // 根据id获取文章数据
        $.ajax({
            type: "GET",
            url: `/my/article/cates/${ id }`,
            success: function (response) {
                // console.log(response);
                // 为表单赋值
                layui.form.val('editForm', response.data);
            }
        });
    });

    $('body').on('submit', '#editForm', function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/my/article/updatecate",
            data: $(this).serialize(),
            success: function (response) {
                if (response.status !== 0) return layer.msg('修改失败!');
                layer.msg('修改成功!');
                getArticleCate();
                layer.close(index);
            }
        });
    })

    // 删除
    $('tbody').on('click', '.deleteCate', function () {
        const id = $(this).attr('data-id');
        layer.confirm('确认要删除吗？', { icon: 3, title: '提示' }, function (index) {
            $.ajax({
                type: "GET",
                url: `/my/article/deletecate/${ id }`,
                success: function (response) {
                    if (response.status !== 0) {
                        return layer.msg('删除失败!');
                    }
                    layer.msg('删除成功!');
                    getArticleCate();
                    layer.close(index);
                }
            });
        })
    })
})

// 获取文章分类列表
function getArticleCate() {
    $.ajax({
        type: "GET",
        url: "/my/article/cates",
        success: function (response) {
            if (response.status !== 0) {
                return layer.msg('获取文章列表失败!');
            }
            const htmlStr = template('tpl-art', response);
            $('tbody').html(htmlStr);
        }
    });
}